# coding:utf-8

import tornado.web
import tornado.ioloop
import tornado.options
import tornado.httpserver
import json
import torndb
import time
import tornado.gen

from tornado.options import options
from tornado.web import RequestHandler
from tornado.httpclient import AsyncHTTPClient

tornado.options.define("port", default=8000, type=int, help="run server on the given port")


class BaseHandler(RequestHandler):
    """请求处理基类"""
    def prepare(self):
        if self.request.headers.get("Content-Type", "").startswith("application/json"):
            try:
                self.json_args = json.loads(self.request.body)
            except Exception as e:
                self.json_args = {}


class IndexHandler(BaseHandler):
    """请求处理类"""
    @tornado.web.asynchronous
    def get(self):
        ip = self.get_argument("ip")
        url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=%s" % ip
        client = AsyncHTTPClient()
        client.fetch(url, callback=self.on_response)

    def on_response(self, resp):
        if not resp.error:
            data = json.loads(resp.body)
            city = data.get("city", "")
            self.write(city)
            self.finish()


class GenHandler(BaseHandler):
    """请求处理类"""
    @tornado.gen.coroutine
    def get(self):
        ip = self.get_argument("ip")
        url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=%s" % ip
        client = AsyncHTTPClient()
        resp = yield client.fetch(url)
        if not resp.error:
            data = json.loads(resp.body)
            city = data.get("city", "")
            self.write(city)


class Gen2Handler(BaseHandler):
    """请求处理类"""
    @tornado.gen.coroutine
    def get(self):
        # ip = self.get_argument("ip")
        # city = yield self.get_ip_city(ip)
        ip1 = "182.48.112.81"
        ip2 = "182.48.112.82"
        ip3 = "182.48.112.83"
        ip4 = "182.48.112.84"
        rep1, rep2 = yield [self.get_ip_city(ip1), self.get_ip_city(ip2)]
        rep34_dict = yield dict(rep3=self.get_ip_city(ip3), rep4=self.get_ip_city(ip4))
        self.write("city1: %s<br/>" % rep1)
        self.write("city2: %s<br/>" % rep2)
        self.write("city3: %s<br/>" % rep34_dict["rep3"])
        self.write("city4: %s<br/>" % rep34_dict["rep4"])

    @tornado.gen.coroutine
    def get_ip_city(self, ip):
        url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=%s" % ip
        client = AsyncHTTPClient()
        resp = yield client.fetch(url)
        if not resp.error:
            data = json.loads(resp.body)
            city = data.get("city", "")
            # return  city 错误
            raise tornado.gen.Return(city)


class Application(tornado.web.Application):
    """"""
    def __init__(self, *args, **kwargs):
        super(Application, self).__init__(*args, **kwargs)
        self.db = torndb.Connection(
            host="127.0.0.1",
            database="itcast",
            user="root",
            password="mysql"
        )


if __name__ == "__main__":
    tornado.options.parse_command_line()
    settings = {
        "debug": True,
        "cookie_secret": "CYUqMIFfRxOpPn4p1mJZBL3wgQJfDUwrlCM+JdC7atQ="
    }
    app = Application(
        [
            (r"/", IndexHandler),
            (r"/gen", GenHandler),
            (r"/gen2", Gen2Handler),
        ],
        **settings
    )
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.current().start()